package study.job.xxljob.job._4_;//package study.job.xxljob.job._4_;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * （1）线程池中线程执行任务时 throw exception 时，如果不 catch，线程会被移出线程池
 * （2）
 */
@Slf4j
@Component
public class _9_AsyncJob {

    private static final int CORE_SIZE = 1;

    private static final int MAX_SIZE = 1;

    private ThreadPoolExecutor pool;


    @PostConstruct
    public void postConstruct() {
        log.info("post construct");
        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("pool-async-thread-%d")
                .build();
//        pool = MdcThreadPoolHelper.newThreadPool(CORE_SIZE, MAX_SIZE,
//                Queues.newLinkedBlockingQueue(100),
//                threadFactory);
    }

    @PreDestroy
    public void preDestroy() {
        log.info("pre destroy");
        if (!Objects.isNull(pool)) {
            pool.shutdown();
        }
    }

    @XxlJob(value = "asyncJob")
    public ReturnT<String> execute(String param) throws Exception {
        try {
            List<String> dataLt = Arrays.asList("1", "2", "3");
            CountDownLatch latch = new CountDownLatch(dataLt.size());
            dataLt.forEach(data -> {
                pool.execute(() -> {
                    try {
                    } catch (Exception ex) {
                        //
                    } finally {
                        latch.countDown();
                    }
                });
            });
            latch.await();

            return ReturnT.SUCCESS;
        } catch (Exception ex) {
            XxlJobHelper.log(ex);
            return ReturnT.FAIL;
        }
    }
}
